package com.quan.system.web.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.quan.common.base.bean.PageBean;
import com.quan.common.base.bean.ResultBean;
import com.quan.common.biz.support.BaseController;
import com.quan.system.entity.SystemArea;
import com.quan.system.service.SystemAreaService;
import com.quan.system.utils.AreaTreeNode;
import com.quan.system.utils.AreaTreeUtil;

import tk.mybatis.mapper.entity.Condition;

/**
 * <p>
 * 省市县 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2018-11-12
 */
@RestController
@RequestMapping("/system/area")
public class SystemAreaController extends BaseController {

    @Autowired 
    private SystemAreaService service;

	/**
     * 添加
     * @param  entity 实体
     * @return ResultBean
     */
    @PostMapping("/add")
    public Object add(@Valid @RequestBody SystemArea entity, BindingResult bindingResult) {
    	if (bindingResult.hasErrors()) {
			return ResultBean.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
    	SystemArea insertSelective = this.service.insertSelective(entity);
		if (null != insertSelective) {
			return ResultBean.ok();
		} else {
			return ResultBean.failure();
		}
    }

    /**
     * 删除
     * @param id ID
     * @return ResultBean
     */
    @DeleteMapping("/delete/{id}")
    public Object delete(@PathVariable Integer id) {
    	int count = this.service.deleteById(id);
    	if(count > 0) {
    		return ResultBean.ok();
    	} else {
    		return ResultBean.failure("通过ID删除失败：[ " + id + " ]");
    	}
    }
    
    /**
     * 批量删除
     * @param params idList(JSON):["1","2"]
     * @return ResultBean
     */
    @PostMapping("/delete")
    public Object delete(@RequestBody Map<String, Object> params) {
    	if(null != params && !params.isEmpty()) {
    		List<Integer> idList = JSON.parseArray(params.get("idList").toString(), Integer.class);
    		int count = this.service.deleteByIds(StringUtils.join(idList, ","));
        	if(count > 0) {
        		return ResultBean.ok();
        	} else {
        		return ResultBean.failure("通过ID删除失败：[ " + idList + " ]");
        	}
    	}
    	return ResultBean.failure("请选项需要删除的记录");
    }

    /**
     * 修改
     * @param  entity 实体
     * @return ResultBean
     */
    @PostMapping("/update")
    public Object update(@Valid @RequestBody SystemArea entity, BindingResult bindingResult) {
    	if (bindingResult.hasErrors()) {
            return ResultBean.warning(bindingResult.getFieldError().getDefaultMessage().toString()) ;
        }
    	int count = this.service.updateSelective(entity);
    	if(count > 0) {
    		return ResultBean.ok();
    	} else {
    		return ResultBean.failure();
    	}
    }

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return Area
    */
    @GetMapping("/get/{id}")
    public Object get(@PathVariable Integer id) {
    	SystemArea entity = this.service.selectOneById(id);
    	if(null != entity) {
    		return ResultBean.ok(entity);
    	} else {
    		return ResultBean.failure("通过ID查询失败：[ " + id + " ]");
    	}
    }
    
    /**
    * 多条件查询数据列表
    *
    * @param entiy 实体对象（查询条件）
    * @return 分页对象
    */
    @GetMapping(value = "/list")
    public Object list(SystemArea entity) {
		return ResultBean.ok(this.service.selectAll(entity));
    }

    /**
    * 多条件查询分页数据
    *
    * @param entiy 实体对象（查询条件）
    * @return 分页对象
    */
    @GetMapping(value = "/page")
    public Object page(SystemArea entity) {
		return ResultBean.ok(this.service.selectPage(entity, new PageBean(request)));
    }
    
    /**
     * 树状JSON结构
     * @param entity
     * @return
     */
    @GetMapping(value = "/tree")
    public Object tree(SystemArea entity) {
    	List<SystemArea> list = this.service.selectAll();
    	List<AreaTreeNode> treeNodes = new ArrayList<AreaTreeNode>();
    	for (SystemArea area : list) {
    		treeNodes.add(new AreaTreeNode(area.getId(), area.getPid(), area.getName()));
    	}
    	return ResultBean.ok(new AreaTreeUtil().treeMenu(treeNodes));
    }
    
    /**
     * 树状JSON结构
     * @param entity
     * @return
     */
    @GetMapping(value = "/loadAreaRoot")
    public Object loadAreaRoot() {
    	List<Object> list = new ArrayList<Object>() ;
    	
    	Condition condition = new Condition(SystemArea.class);
    	condition.createCriteria().andEqualTo("pid", 0);
    	List<SystemArea> childs = this.service.selectAllByCondition(condition);
    	for (SystemArea area : childs) {
    		
    		Map<String, Object> areaMap = new HashMap<String, Object>() ;
    		areaMap.put("id", area.getId());
    		areaMap.put("pid", area.getPid());
    		areaMap.put("name", area.getName());
    		areaMap.put("latitude", area.getLatitude());
    		areaMap.put("longitude", area.getLongitude());
    		
    		Condition hasCondition = new Condition(SystemArea.class);
    		hasCondition.createCriteria().andEqualTo("pid", area.getId());
			int hasChildChild = this.service.selectCountByCondition(hasCondition) ;
			if(hasChildChild > 0) {
				areaMap.put("leaf", false);
			} else {
				areaMap.put("leaf", true);
			}
			
			list.add(areaMap);
		}
    	return ResultBean.ok(list);
    }
    
    /**
     * 树状JSON结构
     * @param entity
     * @return
     */
    @GetMapping(value = "/loadAreaByPid")
    public Object loadAreaByPid(Integer pid) {
    	List<Object> list = new ArrayList<Object>() ;
    	
    	Condition condition = new Condition(SystemArea.class);
    	condition.createCriteria().andEqualTo("pid", pid);
    	List<SystemArea> childs = this.service.selectAllByCondition(condition);
    	for (SystemArea area : childs) {
    		
    		Map<String, Object> areaMap = new HashMap<String, Object>() ;
    		areaMap.put("id", area.getId());
    		areaMap.put("pid", area.getPid());
    		areaMap.put("name", area.getName());
    		areaMap.put("latitude", area.getLatitude());
    		areaMap.put("longitude", area.getLongitude());
    		
    		Condition hasCondition = new Condition(SystemArea.class);
    		hasCondition.createCriteria().andEqualTo("pid", area.getId());
    		int hasChildChild = this.service.selectCountByCondition(hasCondition) ;
    		if(hasChildChild > 0) {
    			areaMap.put("leaf", false);
    		} else {
    			areaMap.put("leaf", true);
    		}
    		list.add(areaMap);
    	}
    	return ResultBean.ok(list);
    }
    
    /**
     * 更新坐标
     * @param latitude
     * @param longitude
     * @return
     */
    @PostMapping(value = "/updateLocation")
    public Object updateLocation(@RequestBody SystemArea area) {
    	this.service.updateLocation(area) ;
    	return ResultBean.ok();
    }
    
    /**
     * 异步生成Vant Area需要的JSON数据文件
     * @return
     */
    @GetMapping(value = "/asyncGeneratorVantAreaJson")
    public Object asyncGeneratorVantAreaJson() {
    	this.service.asyncGeneratorVantAreaJson();
    	return ResultBean.ok();
    }

}
